<template>
  <div class="comment-box">
    <textarea v-model="comment" placeholder="请输入评论内容" class="comment-input"></textarea>
    <button v-if="props.method == 1" @click="submitComment" class="submit-btn">发表评论</button>
    <button v-else @click="secondaryReview(item)" class="submit-btn">发表评1论</button>
  </div>
</template>

<script  setup>
import axios from 'axios';
import { reactive } from 'vue';
import { onMounted } from 'vue';
import { ref } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute()

const props = defineProps({
  method: String,
  item: Object
})

// console.log(props.item);
console.log(props.method);

const state = reactive({
  name: '',
  avatar: '',
})

// 获取文章的id
// console.log(route.query.id);
const comment = ref('');

// 在会话存储获取用户的信息
const user = JSON.parse(sessionStorage.getItem('useInfo'))
// console.log(user['username']);

// 获取用户的头像，昵称
onMounted(async () => {
  const userData = await axios.post('/blog/idFindUserData', {
    id: user.id
  })
  state.name = userData.data[0].nickname
  state.avatar = userData.data[0].avatar
  // console.log(userData.data[0].avatar);
  // console.log(userData.data[0].nickname);
})


// 点击提交评论
const submitComment = async () => {
  if (comment.value.trim()) {
    console.log('提交的评论：', comment.value);
    const result = await axios.post('/comment/submitComment', {
      userid: route.query.id,
      commentor: state.name,
      avatar: state.avatar,
      content: comment.value,
    })
    // console.log(result);
    location.reload();
  } else {
    alert('评论内容不能为空');
  }
};

// 二级评论
const secondaryReview = async (item) => {
  if (comment.value.trim()) {
  const result = await axios.post('/comment/submitSecondaryComment', {
    name: props.item.name,
    replierName: state.name,
    replierContent: comment.value,
    replierAvatar: state.avatar,
    commentId: props.item.name
  })
  // console.log(comment.value);
  // console.log(result);
    location.reload();
  }
  else {
    alert('评论内容不能为空');
  }
}

</script>

<style scoped>
.comment-box {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-bottom: 20px;
  margin-top: 0px;

}

.comment-input {
  width: 100%;
  height: 24px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  /* 禁止调整大小 */
}

.submit-btn {
  width: auto;
  height: 45px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #3e9676;
}
</style>
